<template>
	<div class="system-dicManager-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="900px">

			<el-card shadow="hover">
				<el-form ref="editDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="80px">
					<el-row :gutter="35">

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="排序" prop="sort">
								<el-input v-model="state.ruleForm.sort" placeholder="排序" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="图片描述" prop="photoDesc">
								<el-input v-model="state.ruleForm.photoDesc" placeholder="图片描述" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="状态" prop="status">
								<el-select clearable v-model="state.ruleForm.status">
									<el-option label="启用" value="1"></el-option>
									<el-option label="禁用" value="0"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="类型" prop="photoType">
								<el-select clearable v-model="state.ruleForm.photoType">
									<!-- <el-option label="启动页" value="LAUNCH_PAGE"></el-option> -->
									<el-option label="Banner" value="BANNER"></el-option>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="语言类型" prop="languageType">
								<el-select clearable v-model="state.ruleForm.languageType">
									<!-- <el-option label="中文" value="1"></el-option> -->
									<el-option label="英文" :value="2"></el-option>
									<el-option label="中文繁体" :value="3"></el-option>
									<el-option label="越南语" :value="4"></el-option>
									<el-option label="日语" :value="5"></el-option>
									<el-option label="韩语" :value="6"></el-option>
									<el-option label="泰语" :value="7"></el-option>
								</el-select>
							</el-form-item>
						</el-col>



						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="跳转地址" prop="jumpUrl">
								<el-input v-model="state.ruleForm.jumpUrl" placeholder="跳转地址" clearable></el-input>
							</el-form-item>
						</el-col>




						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="上传图片" prop="imageUrl">
								<el-upload ref="uploadRef" class="avatar-uploader" :accept="'image/*'" :limit="1"
									:on-exceed="handleExceed" :action="uploadActionUrl()" :data="state.uploadParams"
									:headers="state.headers" :show-file-list="false" :before-upload="changeUpload"
									:on-success="handleAvatarSuccess" :on-error="handleAvatarError">
									<img v-if="state.ruleForm.imageUrl" :src="state.ruleForm.imageUrl" class="avatar" />
									<el-icon v-else class="avatar-uploader-icon">
										<Plus />
									</el-icon>
								</el-upload>
							</el-form-item>
						</el-col>






					</el-row>
				</el-form>


			</el-card>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script setup lang="ts" name="systemDicDialog">
import { ElMessage, genFileId } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref, watch } from 'vue';

import { Session } from '/@/utils/storage';




// 导入接口
import { useCommonApi } from '/@/api/common/index'


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const rules = {
	status: [
		{ required: true, message: "请选择状态", trigger: "blur" }
	],
	photoType: [
		{ required: true, message: "请选择类型", trigger: "blur" }
	],
	imageUrl: [
		{ required: true, message: "请选择图片", trigger: "blur" }
	]
}


const uploadRef = ref();
const editDialogFormRef = ref();


const state = reactive({
	row: null as any,
	headers: { Authorization: Session.get('token') },
	uploadParams: {
		remark: "图片资源", // 备注
		tag: "photoImg", // 文件标签，随便输入
		fileAuthRange: "public" // resource 为资源文件 personal 个人文件  public 公开文件
	},
	ruleForm: {
		status: "",
		languageType: "",
		sort: "",
		photoDesc: "",
		photoType: "",
		jumpUrl: "",
		imageUrl: ""
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});



// 打开弹窗
const openDialog = async (type: string, row?: any) => {

	if (uploadRef && uploadRef.value) {
		uploadRef.value!.clearFiles()
	}



	if (type === 'edit') {
		state.row = row;
		state.ruleForm = {
			status: row.status.toString(),
			languageType: row.languageType.toString(),
			sort: row.sort,
			photoDesc: row.photoDesc,
			photoType: row.photoType,
			jumpUrl: row.jumpUrl,
			imageUrl: row.imageUrl
		}
		state.dialog.title = '修改图片';
		state.dialog.submitTxt = '修 改';
	} else {
		state.ruleForm = {
			status: "",
			languageType: "",
			sort: "",
			photoDesc: "",
			photoType: "",
			jumpUrl: "",
			imageUrl: ""
		}

		state.dialog.title = '新增图片';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async () => {

	editDialogFormRef.value.validate(async (valid: any) => {
		if (valid) {
			//检查参数列表
			try {

				if (state.dialog.type == 'edit') {
					let vo = state.ruleForm as any;
					vo['id'] = state.row.id;
					await useCommonApi().updatePhoto(vo);
				} else {
					let vo = state.ruleForm as any;
					await useCommonApi().addPhoto(vo);
				}

				ElMessage.success("操作成功");
				closeDialog(); // 关闭弹窗
				emit('refresh');

			} catch (error: any) {
				ElMessage.error("操作失败请稍后再试");
			}




		} else {
			ElMessage.warning("请检查数据的正确性！");
		}
	})


};

const uploadActionUrl = () => {
	return (
		import.meta.env.VITE_PHOTO_API_URL + "/COMMON-SERVICE/personal/mongo/gridfs/upload"
	);
};



const handleExceed = (files: any) => {
	console.log('cccc')
	uploadRef.value!.clearFiles()
	const file = files[0] as any;
	file.uid = genFileId()
	uploadRef.value!.handleStart(file)
	uploadRef.value.submit();
}


const changeUpload = (rawFile: any) => {
	rawFile = rawFile;
	if (rawFile.type.indexOf('image') < 0) {
		ElMessage.error('请上传图片文件')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片文件不能大于2M')
		return false
	}
	return true
}




const handleAvatarSuccess = async (
	response: { data: any; },
	uploadFile: any
) => {
	state.ruleForm.imageUrl = `${import.meta.env.VITE_PHOTO_API_URL}/COMMON-SERVICE/public/mongo/gridfs/showFile?_id=${response.data}`;
}


const handleAvatarError = (error: any) => {
	state.ruleForm.imageUrl = "";
	ElMessage.warning('上传失败');
}






watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
		}
	}, { immediate: true }
);




// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss">
.el-select {
	width: 100% !important;
}



.system-dicManager-dialog-container {
	.bar_tools {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.el-table__expanded-cell {
		padding: 20px;
	}
}


.avatar-uploader {
	display: flex;
	justify-content: center;
	// width: 100%;

	img {
		width: 178px;
		min-height: 178px;
	}
}


.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>